/**
 * 描述:测试文本宽度
 *  */
export const getTextWidth = (text: string, font = '12px Microsoft Yahei') => {
  const canvas = document.createElement('canvas');
  canvas.id = '__canvas__';
  document.body.append(canvas);
  const kanvas = document.querySelector('#__canvas__') as HTMLCanvasElement;
  const ctx = kanvas.getContext('2d') as CanvasRenderingContext2D;
  ctx.font = font;
  ctx.textBaseline = 'middle';
  const info = ctx.measureText(text);
  canvas.remove();
  return info;
};

const createDom = (config: any, text: string) => {
  const div = document.createElement('div');
  div.hidden = true;
  div.innerHTML = text;
  div.style.display = 'inline-block';
  div.style.fontFamily = config.fontFamily;
  div.style.lineHeight = 'normal';
  div.style.whiteSpace = config.wrap;
  div.style.fontSize = `${config.fontSize}px`;
  document.body.append(div);
  return div;
};
export const getTextDomRect = (config: any) => {
  const div = createDom(config, config.text);
  const domRect = div.getBoundingClientRect();
  div.remove();
  return domRect;
};
export const getTextStyle = (config: any) => {
  const div = createDom(config, config.text);
  const style = getComputedStyle(div);
  div.remove();
  return style;
};
export const downloadText = (text: string, filename = 'text') => {
  const element = document.createElement('a');
  element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`);
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
};
/**
 * 描述:过滤布尔值
 *  */
export const filterBoolean = (bool: boolean, _true = '', _false = '') => {
  return bool ? _true : _false;
};
type position = { x: number; width: number; y: number; height: number };
export const collide = (rect1: position, rect2: position) => {
  let maxX;
  let maxY;
  let minX;
  let minY;
  // eslint-disable-next-line prefer-const
  maxX =
    rect1.x + rect1.width >= rect2.x + rect2.width ? rect1.x + rect1.width : rect2.x + rect2.width;
  // eslint-disable-next-line prefer-const
  maxY =
    rect1.y + rect1.height >= rect2.y + rect2.height
      ? rect1.y + rect1.height
      : rect2.y + rect2.height;
  // eslint-disable-next-line prefer-const
  minX = rect1.x <= rect2.x ? rect1.x : rect2.x;
  // eslint-disable-next-line prefer-const
  minY = rect1.y <= rect2.y ? rect1.y : rect2.y;

  if (maxX - minX <= rect1.width + rect2.width && maxY - minY <= rect1.height + rect2.height) {
    return true;
  }
  return false;
};
export function isImage(fileName: string) {
  const suffix = `(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|jpeg)`;
  const regular = new RegExp(`.*\\.${suffix}`);
  return regular.test(fileName);
}
